package com.syx.system.Service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.syx.common.redis.Service.RedisService;
import com.syx.commoncore.Constant.HttpConstants;
import com.syx.commoncore.Controller.BaseController;
import com.syx.commoncore.Model.LoginUser;
import com.syx.commoncore.Model.Result;
import com.syx.commoncore.enums.Resultcode;
import com.syx.commoncore.enums.UserIdEnum;
import com.syx.security.Exception.ServiceException;
import com.syx.security.Service.TokenService;
import com.syx.system.Mapper.sysuser.SysUserMapper;

import com.syx.system.Model.sysUser.SysUser;
import com.syx.system.Model.sysUser.DTO.SysUserSaveDTO;
import com.syx.system.Model.sysUser.VO.LoginUserVO;
import com.syx.system.Service.ISysUserService;
import com.syx.system.Utils.BCryptUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
//不需要将服务重启就可以使得配置生效
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {

    @Value("${jwt.secret}")
    private String secret;

    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    TokenService tokenService;

    @Override
    public Result login(String userAccount, String password) {

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper.select(SysUser::getUserId,SysUser::getPassword,SysUser::getNickName).eq(SysUser::getUserAccount,userAccount));
        if (sysUser==null){
            return Result.failure(Resultcode.FAILED_USER_NOT_EXISTS.getCode(),Resultcode.FAILED_USER_NOT_EXISTS.getMessage());
        }
        if(BCryptUtils.matchesPassword(password,sysUser.getPassword())){


            //将token放入redis中,通过创建claim来进行token创建
            String token = tokenService.createToken(sysUser.getUserId(),secret,UserIdEnum.ADMIN.getValue(),sysUser.getNickName());


            return Result.success(token);

        }
        //失败的情况
        return Result.failure(Resultcode.FAILED_LOGIN);

    }

    @Override
    public Result<Void> add(SysUserSaveDTO sysUserSaveDTO) {
        //找到有相同名字的人，就无法添加相同名字的新用户
        List<SysUser> sysUsers = sysUserMapper.selectList
                (new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));///////

        if (CollectionUtil.isNotEmpty(sysUsers)){

            throw new ServiceException(Resultcode.AILED_USER_EXISTS.getMessage());

        }

        SysUser sysUser=new SysUser();
        if ( sysUserSaveDTO.getUserAccount()==null || sysUserSaveDTO.getPassword()==null){
            return Result.failure();
        }
        /*sysUser.setUserId();不用设置，因为会*/
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        //生成密文
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        /*sysUser.setCreateBy(1L);

        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setUpdateBy(10L);
        sysUser.setUpdateTime(LocalDateTime.now());*/
        int row = sysUserMapper.insert(sysUser);
        //
        return BaseController.toResult(row);
    }
    //返回用户信息需要先解析token
    @Override
    public Result<LoginUserVO> info(String token) {
        //解析token,获取用户的信息
        if (StrUtil.isNotEmpty(token) &&
                token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);

        if (loginUser==null){
            throw new ServiceException(Resultcode.FAILED_USER_NOT_EXISTS.toString());
        }


        LoginUserVO loginUserVO=new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return Result.success(loginUserVO);


    }

    @Override
    public Result<Void> logout(String token) {
        if (StrUtil.isNotEmpty(token) &&
                token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        tokenService.deleteToken(token,secret);
        return Result.success();


    }
}
